package com.sjx.app.base.utils;

import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.WindowManager;
import android.widget.Toast;

import com.sjx.app.base.BaseApplication;

import java.lang.reflect.Field;

/**
 * 单例Toast
 */
public class ToastUtils {

    private static Toast toast = null;

    public static void show(String s) {
        if (toast == null) {
            toast = Toast.makeText(BaseApplication.sApplication, s, Toast.LENGTH_SHORT);
            //Android 7.x toast的bug
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
                hookToast(toast);
            }
        }
        toast.setText(s);
        toast.show();
    }

    public static void show(int resId) {
        show(BaseApplication.sApplication.getString(resId));
    }

    public static void hookToast(Toast toast) {
        Class<Toast> cToast = Toast.class;
        try {
            //TN是private的
            Field fTn = cToast.getDeclaredField("mTN");
            fTn.setAccessible(true);

            //获取tn对象
            Object oTn = fTn.get(toast);
            //获取TN的class，也可以直接通过Field.getType()获取。
            assert oTn != null;
            Class<?> cTn = oTn.getClass();
            Field fHandle = cTn.getDeclaredField("mHandler");

            //重新set->mHandler
            fHandle.setAccessible(true);
            fHandle.set(oTn, new HandlerProxy((Handler) fHandle.get(oTn)));
        } catch (Exception e) {
            //ignore
        }
    }

    private static class HandlerProxy extends Handler {

        private Handler mHandler;

        public HandlerProxy(Handler handler) {
            this.mHandler = handler;
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                mHandler.handleMessage(msg);
            } catch (WindowManager.BadTokenException e) {
                //ignore
            }
        }
    }
}
